package com.czl.module_storehouse.activity.base;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.CallSuper;
import androidx.viewbinding.ViewBinding;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.data.bean.tengyun.SortBeanKt;
import com.czl.base.util.SpHelper;
import com.czl.module_base.activity.BaseActivity;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_service.event.StorehouseHomeScanEvent;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.intostore.selectgoods.SelectGoodsActivity;
import com.czl.module_storehouse.activity.operation.SelectedProductActivity;
import com.czl.module_storehouse.activity.operation.SelectedSortActivity;
import com.czl.module_storehouse.activity.scan.ScanActivity;
import com.czl.module_storehouse.bean.WorkGroupBean;
import com.czl.module_storehouse.bean.WorkerBean;
import com.czl.module_storehouse.databinding.CommonSelectedOrScanBinding;
import com.czl.module_storehouse.databinding.CommonSelectedOrganizationBinding;
import com.czl.module_storehouse.databinding.FooterCommonRemarkBinding;
import com.czl.module_storehouse.event.OperationEvent;
import com.czl.module_storehouse.event.SelectGoodsEvent;
import com.czl.module_storehouse.event.SelectedProductEvent;
import com.czl.module_storehouse.event.SelectedProductResultEvent;
import com.czl.module_storehouse.mvp.presenter.ProductPresenter;
import com.czl.module_storehouse.utils.QrCodeRuleUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author by xubin,
 * @date on 2022/2/16.
 * PS: Not easy to write code, please indicate.
 */
public abstract class BaseOperationActivity<V extends ViewBinding> extends BaseActivity<V> {

    protected int mSelectedPosition;
    protected FooterCommonRemarkBinding mFooterBinding;

    protected String mOrganizationId;
    private String mLastOrgId;
    protected List<WorkGroupBean> mWorkGroupBeanList;

    protected WorkerBean mWorkerBean;
    protected List<WorkerBean> mWorkerBeanList;
    protected CommonSelectedOrScanBinding mCommonSelectedOrScanBinding;
    protected CommonSelectedOrganizationBinding mCommonSelectedOrganizationBinding;
    protected boolean homeScan;

    @CallSuper
    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        getAdapter().setOnItemClickListener((adapter, view, position) -> {
        });
        getButton().setOnClickListener(v -> submit());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initSelectedScanGoods();
        initSelectedOrganization();
        LiveEventBus.get(StorehouseHomeScanEvent.class).observe(this, event -> {
            homeScan = true;
            getAdapter().addData(event.getSortBean());
            getButton().setEnabled(true);
        });
    }

    protected void submit() {
    }

    protected ViewGroup selectedOrganizationView() {
        return null;
    }

    protected void initSelectedOrganization() {
        if (selectedOrganizationView() != null) {
            mCommonSelectedOrganizationBinding = CommonSelectedOrganizationBinding.inflate(getLayoutInflater(), selectedOrganizationView(), true);
            mCommonSelectedOrganizationBinding.stvOrganization.setOnClickListener(v -> getOrganization());
            mCommonSelectedOrganizationBinding.stvPersonnel.setOnClickListener(v -> getPersonnel());
        }
    }

    protected ViewGroup selectedScanContainerView() {
        return null;
    }

    protected void initSelectedScanGoods() {
        if (selectedScanContainerView() != null) {
            mCommonSelectedOrScanBinding = CommonSelectedOrScanBinding.inflate(getLayoutInflater(), selectedScanContainerView(), true);
            mCommonSelectedOrScanBinding.textSelected.setOnClickListener(v -> goSelectedGoodsActivity());
            mCommonSelectedOrScanBinding.textScan.setOnClickListener(v -> goScanActivity());
        }
    }

    protected void goSelectedGoodsActivity() {
        EventBus.getDefault().postSticky(new OperationEvent(getAdapter().getData()));
        Intent intent = new Intent(getContext(), SelectGoodsActivity.class);
        intent.putExtra("isHiddenAddGoods", true);
        startActivity(intent);
    }

    protected final ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result != null && result.getData() != null) {
                    String stringResult = result.getData().getStringExtra(ScanActivity.RESULT);
                    String productResult = QrCodeRuleUtils.handleStorehouseProductResult(stringResult);
                    if (getProductPresenter() != null) {
                        getProductPresenter().getProductInfoByCode(productResult);
                    }
                }
            });

    protected void goScanActivity() {
        mLauncher.launch(new Intent(getContext(), ScanActivity.class));
    }

    /**
     * 获取适配器
     *
     * @return
     */
    protected abstract BaseQuickAdapter<SortBean, ?> getAdapter();

    /**
     * title
     *
     * @return
     */
    protected String getOperationTitle() {
        return null;
    }

    /**
     * button
     *
     * @return
     */
    protected abstract Button getButton();

    protected ProductPresenter getProductPresenter() {
        return null;
    }

    protected void addFooterView(BaseQuickAdapter<?, ?> adapter) {
        mFooterBinding = FooterCommonRemarkBinding.inflate(getLayoutInflater());
        adapter.addFooterView(mFooterBinding.getRoot());
    }

    protected void startActivity(int position) {
        startActivity(position, null);
    }

    protected void startActivity(int position, View view) {
        if (position < 0) {
            return;
        }
        mSelectedPosition = position;
        SortBean sortBean = getAdapter().getData().get(position);
        SelectedProductEvent event = new SelectedProductEvent(sortBean, getOperationTitle());

        if (1 == sortBean.manageMode() && sortBean.pasteCode()) {
            List<ProductBean> productList = new ArrayList<>();
            for (SortBean bean : getAdapter().getData()) {
                if (bean.getProductBean() != null) {
                    productList.add(bean.getProductBean());
                }
            }
            event.setProductBeanList(productList);
            EventBus.getDefault().postSticky(event);
            startActivity(new Intent(getContext(), SelectedProductActivity.class));
        } else {
            event.setMaxNum(getMaxNum(sortBean));
            EventBus.getDefault().postSticky(event);
            startActivity(new Intent(getContext(), SelectedSortActivity.class));
        }
    }

    protected int getMaxNum(SortBean sortBean) {
        return sortBean.actionableNum();
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(SelectedProductResultEvent event) {
        if (event != null) {
            SortBean sortBean = getAdapter().getData().get(mSelectedPosition);
            getAdapter().setData(mSelectedPosition, sortBean);
            setButtonState();
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(SelectGoodsEvent event) {
        if (event != null) {
            handleSelectedGoods(event.getSortBeanList());
        }
    }

    protected void handleSelectedGoods(List<SortBean> list) {
        getAdapter().addData(list);
    }

    protected void setButtonState() {
        getButton().setEnabled(getTotalCount() > 0);
    }

    protected void setButtonState(int count) {
        getButton().setEnabled(count > 0);
    }

    protected void getOrganization() {
        if (mWorkGroupBeanList == null) {
            selectOrganization();
        } else {
            showPopupWindowGroup();
        }
    }

    protected void selectOrganization() {

    }

    protected void getPersonnel() {
        if (TextUtils.isEmpty(mOrganizationId)) {
            showToast("请先选择部门");
            return;
        }
        if (mWorkerBeanList == null) {
            selectUsersByCompanyId();
        } else {
            showPopupWindowUsers();
        }
    }

    protected void selectUsersByCompanyId() {

    }

    protected void addChildWorkGroup(List<WorkGroupBean> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        for (WorkGroupBean groupBean : list) {
            if (mWorkGroupBeanList == null) {
                mWorkGroupBeanList = new ArrayList<>();
            }
            mWorkGroupBeanList.add(groupBean);
            addChildWorkGroup(groupBean.getChild());
        }
    }

    protected void showPopupWindowGroup() {
        if (mWorkGroupBeanList == null || mWorkGroupBeanList.size() == 0) {
            showToast("没有部门");
            return;
        }
        List<String> list = new ArrayList<>();
        for (WorkGroupBean bean : mWorkGroupBeanList) {
            String orgName = bean.getOrgName();
            if (!TextUtils.isEmpty(orgName)) {
                list.add(orgName);
            }
        }
        showRecyclerViewPopupWindow(list, "选择部门", (adapter, view, position) -> {
            WorkGroupBean bean = mWorkGroupBeanList.get(position);
            mCommonSelectedOrganizationBinding.stvOrganization.setRightString(bean.getOrgName());
            mOrganizationId = bean.getOrganizationId();
            if (!TextUtils.isEmpty(mOrganizationId)) {
                if (!mOrganizationId.equals(mLastOrgId)) {
                    mWorkerBeanList = null;
                }
            }
            if (mLastOrgId != null && !mLastOrgId.equals(mOrganizationId)) {
                mCommonSelectedOrganizationBinding.stvPersonnel.setRightString(getString(R.string.selected_user_placeholder, getOperationTitle()));
            }
            mLastOrgId = mOrganizationId;
        });
    }

    protected void showPopupWindowUsers() {
        if (mWorkerBeanList == null || mWorkerBeanList.size() == 0) {
            showToast("没有人员");
            return;
        }
        List<String> list = new ArrayList<>();
        for (WorkerBean bean : mWorkerBeanList) {
            String tname = bean.getTname();
            if (!TextUtils.isEmpty(tname)) {
                list.add(tname);
            }
        }
        showRecyclerViewPopupWindow(list, "选择人员", (adapter, view, position) -> {
            mWorkerBean = mWorkerBeanList.get(position);
            mCommonSelectedOrganizationBinding.stvPersonnel.setRightString(mWorkerBean.getTname());
        });
    }

    protected int getTotalCount() {
        if (getAdapter().getData().isEmpty()) {
            return 0;
        }
        int count = 0;
        for (SortBean bean : getAdapter().getData()) {
            List<ProductBean> productList = bean.getProductList();
            if (productList != null) {
                count += productList.size();
            }
            count += bean.totalStockNum();
            count += bean.excNum();
        }
        return count;
    }

    protected int getTotalRemandCount() {
        if (getAdapter().getData().isEmpty()) {
            return 0;
        }
        int count = 0;
        for (SortBean bean : getAdapter().getData()) {
            List<ProductBean> productList = bean.getProductList();
            if (productList != null) {
                count += productList.size();
            }
            count += bean.excNum();
            if (bean.pasteCode()) {
                List<LocatListBean> locatList = bean.getLocatList();
                if (locatList == null || locatList.isEmpty()) {
                    continue;
                }
                for (LocatListBean listBean : locatList) {
                    if (listBean.getProductList() == null) {
                        continue;
                    }
                    count += listBean.getProductList().size();
                }
            } else {
                count += bean.totalStockNum();
            }
        }
        return count;
    }

    protected int getTotalCountNum() {
        if (getAdapter().getData().isEmpty()) {
            return 0;
        }
        int count = 0;
        for (SortBean bean : getAdapter().getData()) {
            List<ProductBean> productList = bean.getProductList();
            if (productList != null) {
                count += productList.size();
            }
            count += bean.totalStorageNumNum();
            count += bean.excNum();
        }
        return count;
    }

    protected int getReceiveOrBorrowCount() {
        if (getAdapter().getData().isEmpty()) {
            return 0;
        }
        int total = 0;
        for (SortBean bean : getAdapter().getData()) {
            total += bean.getReceiveCount();
            List<ProductBean> productList = bean.getProductList();
            if (productList != null) {
                total += productList.size();
            }
            ProductBean productBean = bean.getProductBean();
            if (productBean != null) {
                total += 1;
            }
        }
        return total;
    }

    protected List<SortBean> getNewList() {
        List<SortBean> newList = new ArrayList<>();
        getAdapter().getData();
        if (getAdapter().getData().isEmpty()) {
            return newList;
        }
        for (SortBean sortBean : getAdapter().getData()) {
            if (sortBean.getChangeReceiveNum() != null && sortBean.getChangeReceiveNum() > 0) {
                sortBean.setApplyNum(sortBean.getChangeReceiveNum());
            }
            newList.add(sortBean);
        }
        return newList;
    }

    protected void setReceiveOrBorrowEnable() {
        if (getAdapter().getData().isEmpty()) {
            getButton().setEnabled(false);
            return;
        }
        for (SortBean bean : getAdapter().getData()) {
            List<ProductBean> productList = bean.getProductList();
            if (productList != null && !productList.isEmpty()) {
                getButton().setEnabled(true);
            }
            ProductBean productBean = bean.getProductBean();
            if (productBean != null) {
                getButton().setEnabled(true);
                break;
            }
        }
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (ProductPresenter.TAG_PRODUCT_INFO_BY_CODE.equals(httpResponse.getRequestTag())) {
            //扫码单品
            addProductBean(httpResponse);
        }
    }

    protected <T> void addProductBean(HttpResponse<T> httpResponse) {
        if (httpResponse.getData() == null) {
            return;
        }
        Object data = httpResponse.getData();
        if (data instanceof ProductBean) {
            ProductBean productBean = (ProductBean) httpResponse.getData();
            if (productBean == null) {
                return;
            }
            if (productBean.getStorehouseLocatId() == null || productBean.getStorehouseLocatId() == 0) {
                showToast("该物品不存在");
                return;
            }
            if (productBean.getStorehouseId() == null
                    || productBean.getStorehouseId() != SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_ID)) {
                showToast("不是该仓库物品");
                return;
            }
            if (getProductBean(productBean, getAdapter().getData()) == null) {
                productBean.setManufactureDate(null);
                SortBean sortBean = SortBeanKt.createProductSortBean(productBean);
                getAdapter().addData(sortBean);
                getButton().setEnabled(true);
            } else {
                showToast("该物品已添加");
            }
        }
    }

    public SortBean getProductBean(ProductBean productBean, List<SortBean> list) {
        if (list == null) {
            return null;
        }

        for (SortBean bean : list) {
            if (bean.getProductBean() == null) {
                continue;
            }
            if (bean.getProductBean().getProductId() == null) {
                continue;
            }
            if (bean.getProductBean() != null) {
                if (bean.getProductBean().getProductId().equals(productBean.getProductId())) {
                    return bean;
                }
            } else {
                List<ProductBean> productList = bean.getProductList();
                if (productList != null && !productList.isEmpty()) {
                    for (ProductBean productBean1 : productList) {
                        if (productBean1.getProductId() == null) {
                            continue;
                        }
                        if (productBean1.getProductId().equals(productBean.getProductId())) {
                            return bean;
                        }
                    }
                }
            }
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mFooterBinding != null) {
            mFooterBinding.unbind();
        }
        if (mCommonSelectedOrScanBinding != null) {
            mCommonSelectedOrScanBinding.unbind();
        }
        if (mCommonSelectedOrganizationBinding != null) {
            mCommonSelectedOrganizationBinding.unbind();
        }
    }
}
